<template>
  <div class="min-h-screen bg-gray-50">
    <div class="py-4 text-center bg-primary">
      <h1 class="text-2xl font-bold text-white">动态聚合码测试</h1>
    </div>

    <div class="max-w-md mx-auto p-4">
      <!-- 订单信息表单 -->
      <a-card class="mb-4 shadow-sm">
        <h2 class="text-lg font-bold mb-4">订单信息</h2>

        <a-form :model="orderForm" layout="vertical">
          <a-form-item label="订单ID" name="orderId">
            <div class="flex">
              <a-input v-model:value="orderForm.orderId" placeholder="订单ID" readonly class="flex-1" />
              <a-button type="primary" class="ml-2" @click="generateOrderId">刷新</a-button>
            </div>
          </a-form-item>

          <a-form-item label="商品名称" name="title" required>
            <a-input v-model:value="orderForm.title" placeholder="请输入商品名称" />
          </a-form-item>

          <a-form-item label="支付金额" name="amount" required>
            <a-input-number
              v-model:value="orderForm.amount"
              :precision="2"
              :min="0.01"
              :max="50000"
              placeholder="请输入金额"
              style="width: 100%;"
            />
          </a-form-item>

          <a-form-item label="备注信息" name="description">
            <a-input v-model:value="orderForm.description" placeholder="请输入备注信息" />
          </a-form-item>

          <a-form-item>
            <a-button type="primary" block size="large" @click="createPayment" :disabled="!isFormValid">
              生成支付码
            </a-button>
          </a-form-item>
        </a-form>
      </a-card>

      <!-- 支付二维码弹窗 -->
      <a-modal
        v-model:open="qrCodeVisible"
        title="聚合支付码"
        :footer="null"
        :maskClosable="false"
        width="320px"
      >
        <div class="text-center">
          <div class="mb-4">
            <img v-if="qrCodeUrl" :src="qrCodeUrl" alt="支付码" class="mx-auto" style="width: 200px; height: 200px;" />
            <a-spin v-else />
          </div>
          <p class="text-lg font-bold mb-2">¥{{ orderForm.amount.toFixed(2) }}</p>
          <p class="text-sm text-gray-500 mb-4">{{ orderForm.title }}</p>
          <div class="flex justify-center items-center gap-4 mb-2">
            <div class="flex items-center">
              <wechat-outlined style="color: #07C160; font-size: 24px;" />
              <span class="text-gray-500 ml-1">微信支付</span>
            </div>
            <div class="flex items-center">
              <alipay-circle-outlined style="color: #1677FF; font-size: 24px;" />
              <span class="text-gray-500 ml-1">支付宝</span>
            </div>
          </div>
          <p class="text-sm text-gray-400">支付码有效期：{{ countdown }}秒</p>

          <!-- 支付状态 -->
          <div v-if="payStatus === 'PAYING'" class="mt-4">
            <a-spin />
            <p class="mt-2 text-gray-500">正在查询支付结果...</p>
          </div>
          <div v-else-if="payStatus === 'SUCCESS'" class="mt-4">
            <check-circle-outlined style="color: #52c41a; font-size: 32px;" />
            <p class="mt-2 text-green-500">支付成功</p>
          </div>
          <div v-else-if="payStatus === 'FAILED'" class="mt-4">
            <close-circle-outlined style="color: #f5222d; font-size: 32px;" />
            <p class="mt-2 text-red-500">支付失败</p>
          </div>

          <a-button class="mt-4" @click="closeQRCode">关闭</a-button>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  WechatOutlined,
  AlipayCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons-vue'
import axios from 'axios'

// 订单表单
const orderForm = reactive({
  orderId: `ORDER_${Date.now()}`,
  title: '测试商品',
  amount: 0.01,
  description: ''
})

// 表单验证
const isFormValid = computed(() => {
  return orderForm.title && orderForm.amount > 0
})

// 支付相关状态
const qrCodeUrl = ref('')
const qrCodeVisible = ref(false)
const payStatus = ref('PENDING') // PENDING, PAYING, SUCCESS, FAILED
const countdown = ref(300) // 5分钟
let timer: number

// 生成新的订单ID
const generateOrderId = () => {
  orderForm.orderId = `ORDER_${Date.now()}`
}

// 创建支付订单
const createPayment = async () => {
  if (!isFormValid.value) {
    message.error('请填写完整的订单信息')
    return
  }

  try {
    // 这里应该调用后端API创建支付订单
    // const response = await axios.post('/api/v1/payments', {
    //   orderId: orderForm.orderId,
    //   title: orderForm.title,
    //   amount: orderForm.amount,
    //   description: orderForm.description
    // })

    // 模拟API响应
    const response = {
      data: {
        code: 0,
        data: {
          qrCodeUrl: `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=https://example.com/pay?orderId=${orderForm.orderId}&amount=${orderForm.amount}`,
        }
      }
    }

    if (response.data.code === 0) {
      qrCodeUrl.value = response.data.data.qrCodeUrl
      qrCodeVisible.value = true
      payStatus.value = 'PAYING'
      startPolling()
    }
  } catch (error) {
    console.error('创建支付订单失败:', error)
    message.error('创建支付订单失败')
  }
}

// 查询订单状态
const queryOrderStatus = async () => {
  try {
    // 这里应该调用后端API查询订单状态
    // const response = await axios.get(`/api/v1/payments/${orderForm.orderId}/status`)

    // 模拟API响应
    // 随机模拟支付成功
    const random = Math.random()
    let status = 'PAYING'

    if (countdown.value < 270 && random > 0.7) {
      status = 'SUCCESS'
    }

    const response = {
      data: {
        code: 0,
        data: {
          status: status
        }
      }
    }

    if (response.data.code === 0) {
      const status = response.data.data.status
      payStatus.value = status

      if (status === 'SUCCESS') {
        message.success('支付成功')
        clearInterval(timer)
      } else if (status === 'FAILED') {
        message.error('支付失败')
        clearInterval(timer)
      }
    }
  } catch (error) {
    console.error('查询订单状态失败:', error)
  }
}

// 开始轮询
const startPolling = () => {
  // 重置倒计时
  countdown.value = 300

  timer = window.setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--

      // 每3秒查询一次状态
      if (countdown.value % 3 === 0) {
        queryOrderStatus()
      }
    } else {
      clearInterval(timer)
      message.warning('支付超时，订单已关闭')
      payStatus.value = 'FAILED'
    }
  }, 1000) // 每秒更新倒计时
}

// 关闭二维码弹窗
const closeQRCode = () => {
  qrCodeVisible.value = false
  clearInterval(timer)
  payStatus.value = 'PENDING'
}

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.bg-primary {
  background-color: #1890ff;
}

.ant-card {
  border-radius: 8px;
}
</style>